package com.support.util;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

import com.sun.org.apache.xml.internal.security.utils.Base64;


public class GenerateKeyPair
{
	// 加密方式
	private static final String KEY_ALGORITHM = "RSA";
	
	private static final String PUBLIC_KEY ="PUBLIC_KEY";    
	private static final String PRIVATE_KEY ="PRIVATE_KEY";
	
	public static Map<String,String> genKey() throws NoSuchAlgorithmException
	{    
		return genKey(null);    
	}
	
	// 指定key生成密钥，每次生成的密钥值相同，不建议使用   
	public static Map<String,String> genKey(String keyInfo) throws NoSuchAlgorithmException
	{    
	    Map<String,String> keyMap = new HashMap<String,String>();    
	    
	    KeyPairGenerator keygen = KeyPairGenerator.getInstance(KEY_ALGORITHM);    
	    SecureRandom random = new SecureRandom(); 
	    
	    if(!StringUtils.isEmpty(keyInfo))
	    {
	    	random.setSeed(keyInfo.getBytes());// 指定key生成密钥，每次生成的密钥值相同，不建议使用   
	    }
	    
	    // 初始加密，512位已被破解，用1024位,最好用2048位    
	    keygen.initialize(1024, random);   
	    
	    // 取得密钥对    
	    KeyPair kp = keygen.generateKeyPair();    
	    RSAPrivateKey privateKey = (RSAPrivateKey)kp.getPrivate();    
        String privateKeyString = Base64.encode(privateKey.getEncoded());
        
	    RSAPublicKey publicKey = (RSAPublicKey)kp.getPublic();     
	    String publicKeyString = Base64.encode(publicKey.getEncoded()); 
	    
	    keyMap.put(PUBLIC_KEY, publicKeyString);    
	    keyMap.put(PRIVATE_KEY, privateKeyString); 
	    
	    return keyMap;    
	}
}
